import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import '../config/app_config.dart';

class DioConfig {
  static Dio? _dio;

  static Dio get dio {
    _dio ??= _createDio();
    return _dio!;
  }

  static Dio _createDio() {
    final dio = Dio(BaseOptions(
      baseUrl: AppConfig.apiBaseUrl,
      connectTimeout: const Duration(seconds: 30),
      receiveTimeout: const Duration(seconds: 30),
      sendTimeout: const Duration(seconds: 30),
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
    ));

    // 添加请求拦截器
    dio.interceptors.add(RequestInterceptor());
    
    // 添加响应拦截器
    dio.interceptors.add(ResponseInterceptor());

    // 在调试模式下添加日志拦截器
    if (kDebugMode || AppConfig.debugMode) {
      dio.interceptors.add(LogInterceptor(
        requestBody: true,
        responseBody: true,
        requestHeader: true,
        responseHeader: false,
        error: true,
        logPrint: (obj) => debugPrint(obj.toString()),
      ));
    }

    return dio;
  }

  // 重置Dio实例（用于切换环境时）
  static void reset() {
    _dio?.close();
    _dio = null;
  }
}

// 请求拦截器
class RequestInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // 添加API Key到请求头
    if (AppConfig.apiKey.isNotEmpty) {
      options.headers['Authorization'] = 'Bearer ${AppConfig.apiKey}';
    }
    
    // 添加其他通用请求头
    options.headers['X-App-Version'] = AppConfig.version;
    options.headers['X-Environment'] = AppConfig.environment.value;
    
    debugPrint('🚀 请求: ${options.method} ${options.uri}');
    super.onRequest(options, handler);
  }
}

// 响应拦截器
class ResponseInterceptor extends Interceptor {
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    debugPrint('✅ 响应: ${response.statusCode} ${response.requestOptions.uri}');
    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    debugPrint('❌ 错误: ${err.type} ${err.message}');
    super.onError(err, handler);
  }
}
